package com.kmproject.haifu.mvp.presenter;

import android.app.Activity;
import android.app.Application;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.irozon.library.HideKey;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.CustomPopupWindow;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.RxUtils;
import com.kmproject.haifu.mvp.contract.HomeMainContract;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.HomeBannerBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.QueryAreaByLtLotBean;
import com.kmproject.haifu.mvp.model.entity.beans.SeletCityBean;
import com.kmproject.haifu.mvp.model.entity.resbean.HFLocationBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseMainBean;
import com.kmproject.haifu.mvp.ui.adapter.PopuwindowSelectTypeAdapter;
import com.xw.repo.XEditText;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/08/2019 23:52
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class HomeMainPresenter extends BasePresenter<HomeMainContract.Model, HomeMainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private CustomPopupWindow customPopupWindow;
    private PopuwindowViewHold popuwindowViewHold;
    private HFLocationBean mbdLocation;
    private PopuwindowSelectTypeAdapter popuwindowSelectTypeAdapter;
    private List<SeletCityBean> mseletCityBeans;

    @Inject
    public HomeMainPresenter(HomeMainContract.Model model, HomeMainContract.View rootView) {
        super(model, rootView);
    }

    public CustomPopupWindow getCustomPopupWindow() {
        return customPopupWindow;
    }

    /**
     * 根据经纬度查询区域
     *
     * @param lat
     * @param lgt
     */
    public void getLocationByLngLat(String lat, String lgt) {
        mModel.getLocationByLngLat(lat, lgt).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<QueryAreaByLtLotBean>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<QueryAreaByLtLotBean> queryAreaByLtLotBeanResultBean) {
                        if (AppUtil.isSuccess(queryAreaByLtLotBeanResultBean)) {

                            if (queryAreaByLtLotBeanResultBean.getData().getAreas() == null || queryAreaByLtLotBeanResultBean.getData().getAreas().isEmpty()) {
                                HousePayWayBean housePayWayBean = new HousePayWayBean();
                                housePayWayBean.setName("马尼拉");
                                housePayWayBean.setDictId("");
                                mRootView.selectCitySuccess(housePayWayBean);
                                if (popuwindowViewHold != null) {
                                    popuwindowViewHold.popuwindowSelectCityAddress.setText(housePayWayBean.getName());
                                }
                            } else {
                                mRootView.selectCitySuccess(queryAreaByLtLotBeanResultBean.getData().getAreas().get(0));
                                if (popuwindowViewHold != null) {
                                    popuwindowViewHold.popuwindowSelectCityAddress.setText(queryAreaByLtLotBeanResultBean.getData().getAreas().get(0).getName());
                                }
                            }

                        } else {
                            mRootView.showMessage(queryAreaByLtLotBeanResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取首页banner图
     */
    public void getHomeBanner() {
        mModel.getHomeBanner().compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HomeBannerBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HomeBannerBean>> resultBean) {
                        mRootView.hideLoading();
                        if (AppUtil.isSuccess(resultBean)) {
                            mRootView.getHomeBannerSuccess(resultBean.getData());
                        } else {
                            mRootView.showMessage(resultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取选择的区域
     */
    public void getIndexHouseArea() {
        mModel.getIndexHouseArea().compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<SeletCityBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<SeletCityBean>> housePayWayBeans) {
                        if (AppUtil.isSuccess(housePayWayBeans)) {
                            mRootView.getIndexHouseAreaSuccess(housePayWayBeans.getData());
                        } else {
                            mRootView.showMessage(housePayWayBeans.getMessage());
                        }

                    }
                });
    }

    /**
     * 初始化数据
     *
     * @return
     */
    public List<HouseMainBean.HouseMainItem> getDatas() {

        List<HouseMainBean.HouseMainItem> houseMainItems1 = new ArrayList<>();
        houseMainItems1.add(new HouseMainBean.HouseMainItem("shjf", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.home_main_shjf), R.mipmap.icon_home_category_1, "home"));
        houseMainItems1.add(new HouseMainBean.HouseMainItem("zf", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.home_main_zf), R.mipmap.icon_home_category_2, "home"));
//        houseMainItems1.add(new HouseMainBean.HouseMainItem("qsf", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.home_main_esf), R.drawable.home_esf_icon, "home"));
        houseMainItems1.add(new HouseMainBean.HouseMainItem("qz", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.home_main_qz), R.mipmap.icon_home_category_3, "home"));
        houseMainItems1.add(new HouseMainBean.HouseMainItem("essc", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.home_main_essc), R.mipmap.icon_home_category_4, "home"));

        return houseMainItems1;
    }

    /**
     * 刷新界面
     *
     * @param mbdLocation
     */
    public void setLocation(HFLocationBean mbdLocation) {
        if (popuwindowViewHold != null) {
//            popuwindowViewHold.popuwindowSelectCityAddress.setText(mbdLocation.getMlocation().getProvider());
        }
        this.mbdLocation = mbdLocation;
        getLocationByLngLat(String.valueOf(mbdLocation.getMlocation().getLatitude()), String.valueOf(mbdLocation.getMlocation().getLongitude()));
    }

    /**
     * 控制popu显示选择区域
     */
    public void showPopuWindowToSearch(Activity activity, View view) {
        HideKey.initialize(activity, view);
        DataHelper.setBooleanSF(activity, AppConstant.user_isFirst_login, false);
        customPopupWindow = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(activity, R.layout.popuwindow_select_city)).parentView(view)
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isHaveBackGround(false).build();
        View view1 = customPopupWindow.getContentView();
        popuwindowViewHold = new PopuwindowViewHold(view1);
        popuwindowViewHold.popuwindowSelectCityAddress.setText("定位中...");
        if (mbdLocation != null) {
            //避免定位比初始化快，倒是数据不能回填
            popuwindowViewHold.popuwindowSelectCityAddress.setText(mbdLocation.getMlocation().getProvider());
        }
        popuwindowViewHold.popuwindowSelectCityRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        popuwindowSelectTypeAdapter = new PopuwindowSelectTypeAdapter(null, new PopuwindowSelectTypeAdapter.ClickBack() {
            @Override
            public void callback(int parmentIndex, int childIndex) {
                popuwindowViewHold.popuwindowSelectCityAddress.setText(popuwindowSelectTypeAdapter.getData().get(parmentIndex).getData().get(childIndex).getName());
                mRootView.selectCitySuccess(popuwindowSelectTypeAdapter.getData().get(parmentIndex).getData().get(childIndex));
                customPopupWindow.dismiss();
            }
        });
        popuwindowViewHold.popuwindowSelectCityRecyclerView.setAdapter(popuwindowSelectTypeAdapter);
        popuwindowSelectTypeAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);

        popuwindowViewHold.includeTitleSearchXedit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() < 1) {
                    //输入内容小于1
                    popuwindowSelectTypeAdapter.setNewData(mseletCityBeans);
                } else {
                    popuwindowSelectTypeAdapter.setNewData(searchFortxt(s.toString()));
                }
            }
        });

        popuwindowViewHold.includeTitleSearchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopupWindow.dismiss();
            }
        });
        popuwindowViewHold.popuwindowSelectCityRefersh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popuwindowViewHold.popuwindowSelectCityAddress.setText("定位中");

                //刷新定位
                mRootView.startLocation(true);
            }
        });
        popuwindowViewHold.popuwindowSelectCityAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.show();
    }

    /**
     * 过滤
     *
     * @param name
     * @return
     */
    public List<SeletCityBean> searchFortxt(String name) {
        List<SeletCityBean> temSeletCityBeans = new ArrayList<>();
        if (mseletCityBeans == null || popuwindowSelectTypeAdapter == null || mseletCityBeans.isEmpty()) {
            return temSeletCityBeans;
        }
        SeletCityBean temseletCityBean = null;
        for (SeletCityBean seletCityBean : mseletCityBeans) {
            if (seletCityBean.getDataIndex().contains(name)) {
                temSeletCityBeans.add(seletCityBean);

            } else {

                for (HousePayWayBean housePayWayBean : seletCityBean.getData()) {
                    if (housePayWayBean.getName().contains(name)) {
                        if (temseletCityBean == null) {
                            temseletCityBean = new SeletCityBean();
                            temseletCityBean.setDataIndex(seletCityBean.getDataIndex());
                            temseletCityBean.setData(new ArrayList<>());
                        }
                        temseletCityBean.getData().add(housePayWayBean);
                    }
                }
                if (temseletCityBean != null) {
                    temSeletCityBeans.add(temseletCityBean);
                }
            }
        }
        return temSeletCityBeans;
    }

    /**
     * 获取数据后刷新数据
     *
     * @param datas
     */
    public void refershDatas(List<SeletCityBean> datas) {
        if (popuwindowSelectTypeAdapter != null) {
            mseletCityBeans = datas;
            popuwindowSelectTypeAdapter.setNewData(datas);
        }
    }


    public static class PopuwindowViewHold {

        @BindView(R.id.include_title_search_back)
        ImageView includeTitleSearchBack;
        @BindView(R.id.include_title_search_xedit)
        XEditText includeTitleSearchXedit;
        @BindView(R.id.include_title_search_lay)
        LinearLayout includeTitleSearchLay;
        @BindView(R.id.popuwindow_select_city_address)
        TextView popuwindowSelectCityAddress;
        @BindView(R.id.popuwindow_select_city_refersh_img)
        ImageView popuwindowSelectCityRefershImg;
        @BindView(R.id.popuwindow_select_city_refersh)
        LinearLayout popuwindowSelectCityRefersh;
        @BindView(R.id.popuwindow_select_city_RecyclerView)
        RecyclerView popuwindowSelectCityRecyclerView;
        @BindView(R.id.popuwindow_select_city_RecyclerView1)
        RecyclerView popuwindowSelectCityRecyclerView1;

        public PopuwindowViewHold(View view) {
//            R.layout.popuwindow_select_city
            ButterKnife.bind(this, view);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
}
